﻿using System;
using System.AddIn;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using Bookvar.AddIns.AddInViews;
using Bookvar.Common;
using Bookvar.ObjectModel;
using Interop.WindowsLiveWriter.Application;
using Microsoft.Win32;


namespace Bookvar.AddIns.LiveWriter
{
	[AddIn( "Live Writer AddIn", Version = "1.0.0.0" )]
	public class LiveWriterAddIn : BookvarAddinView
	{
		public override void Execute( Topic topic )
		{
			if ( LiveWriterExists() )
			{
				if ( topic != null )
				{
					Topic mainTopic = topic;

					string blogBody = GetTopicImages( mainTopic ) + GetTopicNotesHtml( mainTopic ) +
					                  GetSubTopicsHtml( mainTopic.SubTopics, 1 );
					WindowsLiveWriterApplicationClass liveWriter = new WindowsLiveWriterApplicationClass();
					liveWriter.BlogThisHtml( mainTopic.Name, blogBody );
				}
			}
			else
			{
				MessageBox.Show( "In order to use this addin you need to have Windows Live Writer installed!", "Windows Live Writer",
				                 MessageBoxButton.OK, MessageBoxImage.Exclamation );
			}
		}

		private static string GetSubTopicsHtml( IEnumerable<Topic> topicCollection, int level )
		{
			StringBuilder result = new StringBuilder();
			foreach ( Topic topic in topicCollection )
			{
				result.AppendFormat( "<h{0}>{1}</h{0}>", level, topic.Name );
				result.Append( GetTopicImages( topic ) );
				result.Append( GetTopicNotesHtml( topic ) );
				result.Append( GetSubTopicsHtml( topic.SubTopics, level + 1 ) );
			}
			return result.ToString();
		}

		private static string GetTopicNotesHtml( Topic topic )
		{
			if ( topic.Note != null )
			{
				FlowDocument doc = new FlowDocument();
				TextRange textRange = new TextRange( doc.ContentStart, doc.ContentEnd );
				using ( MemoryStream stream = new MemoryStream() )
				{
					topic.Note.Save( stream, DataFormats.XamlPackage );
					textRange.Load( stream, DataFormats.XamlPackage );
				}

				return HtmlFromXamlConverter.ConvertXamlToHtml( XamlWriter.Save( doc ) );
			}
			return String.Empty;
		}

		private static string GetTopicImages( Topic topic )
		{
			StringBuilder images = new StringBuilder();
			foreach ( Resource resource in topic.Resources )
			{
				if ( resource.ResourceType == ResourceType.Image )
				{
					string tempFile = SaveImageToTempFile( resource );
					if ( resource.VisualSize.Width > 0 || resource.VisualSize.Height > 0 )
					{
						images.AppendFormat( "<img src=\"file:///{0}\" alt=\"\" style=\"width:{1}px; height: {2}px; \"  />", tempFile,
						                     (int) resource.VisualSize.Width, (int) resource.VisualSize.Height );
					}
					else
					{
						images.AppendFormat( "<img src=\"file:///{0}\" alt=\"\" />", tempFile );
					}
				}
			}
			return images.ToString();
		}

		private static string SaveImageToTempFile( Resource resource )
		{
			BitmapFrame frame = resource.ItemSource as BitmapFrame;
			if ( frame != null )
			{
				string tempFileName = Path.ChangeExtension( Path.GetTempFileName(), ".png" );
				using ( FileStream stream = new FileStream( tempFileName, FileMode.Create ) )
				{
					stream.Write( resource.ResourceBytes, 0, resource.ResourceBytes.Length );
				}
				return tempFileName;
			}
			return String.Empty;
		}

		private static bool LiveWriterExists()
		{
			RegistryKey key = Registry.LocalMachine.OpenSubKey( @"SOFTWARE\Microsoft\Windows Live\Writer\" );
			return ( key != null );
		}


		public override AddinInfo Info
		{
			get
			{
				AddinInfo info = new AddinInfo();
				info.Name = "Live Writer";
				info.Group = "Blog";
				info.Description = "Blog current map to Windows Live Writer";
				info.Image = AssemblyUtility.LoadImageFromResources(
					typeof ( LiveWriterAddIn ).Assembly, "Bookvar.AddIns.LiveWriter.Writer.png" );
				return info;
			}
		}
	}
}